package com.feng.study.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vip.vjtools.vjkit.mapper.JsonMapper;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class JsonUtils {

	public static <T> List<T> jsonToList(String json, Class<T> clazz) {
		JsonMapper jsonMapper = JsonMapper.INSTANCE;
		JavaType javaType = jsonMapper.buildCollectionType(List.class, clazz);
		return jsonMapper.fromJson(json, javaType);
	}

	public static <T> T jsonToBeanByType(String json, TypeReference type) {
		ObjectMapper mapper = JsonMapper.INSTANCE.getMapper();
		try {
			return (T) mapper.readValue(json, type);
		} catch (Exception e) {
			log.error("反序列化失败,json:{},type:{}", json, type);
			return null;
		}
	}

	public static <T> T jsonToBean(String json, Class<T> clazz) {
		JsonMapper jsonMapper = JsonMapper.INSTANCE;
		return jsonMapper.fromJson(json, clazz);
	}

	public static String toJson(Object object){
		JsonMapper jsonMapper = JsonMapper.INSTANCE;
		return jsonMapper.toJson(object);
	}
}
